<template>
  <div class="mobile-confirm-page" v-if="packageInfo">
    <el-card class="confirm-card">
      <h2 class="confirm-title">确认收取任务包</h2>
      <div class="package-info">
        <div><b>任务包编号：</b>{{ packageInfo.packageId }}</div>
        <div><b>配送区域：</b>{{ packageInfo.deliveryArea }}</div>
        <div><b>订单数量：</b>{{ packageInfo.orderCount }}</div>
        <div><b>总配送费：</b>¥{{ packageInfo.totalReward }}</div>
      </div>
      <el-divider>包裹明细</el-divider>
      <el-table :data="packageInfo.orders" border size="small">
        <el-table-column prop="orderNumber" label="订单号" />
        <el-table-column prop="customerName" label="客户" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="reward" label="配送费" />
        <el-table-column prop="remark" label="备注" />
      </el-table>
      <el-button type="primary" style="width:100%;margin-top:20px;" @click="handleConfirm" :loading="loading">
        确认收取
      </el-button>
    </el-card>
  </div>
  <el-empty v-else description="未获取到任务包信息" />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { collectPackage, getTaskPackageDetail } from '@/assets/delivery.js'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const packageInfo = ref(null)
const packageId = ref('')

onMounted(async () => {
  packageId.value = route.query.packageId || route.query.package_id || route.params.packageId
  if (!packageId.value) {
    ElMessage.error('未获取到任务包ID')
    return
  }
  try {
    const res = await getTaskPackageDetail(packageId.value)
    if (res.data && res.data.code === 200 && res.data.data) {
      const data = res.data.data
      packageInfo.value = {
        packageId: data.packageId,
        deliveryArea: data.destination || data.deliveryArea,
        deliveryTime: data.startTime ? data.startTime.replace('T', ' ').slice(0, 16) : '',
        estimatedDistance: data.estimatedDistance || 0,
        orderCount: data.orders ? data.orders.length : 0,
        totalReward: data.orders ? data.orders.reduce((sum, o) => sum + (o.reward || 0), 0) : 0,
        orders: data.orders || [],
        status: data.deliveryStatus
      }
    } else {
      ElMessage.error(res.data?.message || '未获取到任务包信息')
    }
  } catch (e) {
    ElMessage.error('网络错误')
  }
})

const saveCollectedPackageId = (packageId) => {
  packageId = String(packageId)
  let collected = JSON.parse(localStorage.getItem('collectedPackages') || '[]')
  if (!collected.includes(packageId)) {
    collected.push(packageId)
    localStorage.setItem('collectedPackages', JSON.stringify(collected))
    console.log('已存入localStorage:', collected)
  } else {
    console.log('包ID已存在localStorage:', collected)
  }
}

const handleConfirm = async () => {
  loading.value = true
  try {
    console.log('确认揽收包ID:', packageId.value)
    const res = await collectPackage(packageId.value)
    if (res.data && res.data.code === 200) {
      saveCollectedPackageId(packageId.value)
      ElMessage.success('揽收成功')
      if (window.opener) {
        window.opener.postMessage('collected-success', '*')
        window.opener.location.reload()
      }
      setTimeout(() => {
        window.close()
      }, 800)
      packageInfo.value = null
    } else {
      ElMessage.error(res.data?.message || '揽收失败')
    }
  } catch (e) {
    ElMessage.error('网络错误')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.mobile-confirm-page {
  min-height: 100vh;
  background: #f7f8fa;
  display: flex;
  align-items: center;
  justify-content: center;
}
.confirm-card {
  width: 95vw;
  max-width: 420px;
  margin: 0 auto;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.06);
}
.confirm-title {
  text-align: center;
  margin-bottom: 18px;
  font-size: 20px;
  font-weight: bold;
  color: #333;
}
.package-info {
  margin-bottom: 12px;
  font-size: 15px;
  color: #444;
  line-height: 1.8;
}
</style> 